﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using CKS.API.Logging;
using CKS.API.Exceptions;
using System.Web.Caching;
using CKS.API.Contracts;
using System.Collections.Generic;

namespace CKSInstrumentationSandboxTest.SandboxTestWP2
{
    [ToolboxItemAttribute(false)]
    public class SandboxTestWP2 : WebPart
    {
        private CKSSandboxLogger logger = null;



        protected override void OnInit(EventArgs e)
        {
            logger = new CKSSandboxLogger(SPContext.Current.Site.RootWeb, false);

            logger.CatchUnhandledExceptions();

            //A Scope defines a batch of entries written to the log at one time.  You can either create one per request, one per method, or one per code block, depending on your needs.
            //Beginning a new Scope will write out anyhting pending from a previous Scope.
            logger.BeginScope();
            base.OnInit(e);

        }


        protected override void OnPreRender(EventArgs e)
        {
            //EndScope MUST be called in sandbox - recommend to do it once rather than in each method
            logger.EndScope();

            base.OnPreRender(e);
        }


        void NoBigDeal_Click(object sender, EventArgs e)
        {
            //Simulate a situation we can recover from (i.e. an inaccessible configuration setting for which a default value is available)
            //all we do is log - no user display


            //The following lines will be removed from our Release builds automatically
            logger.WriteDebugMethodStart();
            logger.WriteDebug("This is a message that won't show up in our Release build!");

            //call method to retrieve a setting value
            string configSetting = GetConfigSettingOrDefault("mySetting");

            //The following line will be removed from our Release builds automatically
            logger.WriteDebugMethodEnd();


        }

        private string GetConfigSettingOrDefault(string p)
        {
            //The following line will be removed from our Release builds automatically
            logger.WriteDebugMethodStart();

            //Try to get setting here...

            logger.Write(string.Format("Configuration Setting {0} is not available", p), CKSLoggingCategory.General, LoggingSeverity.Warning);

            //The following line will be removed from our Release builds automatically
            logger.WriteDebugMethodEnd();

            return "Default Setting Value";
        }

        void NotSoBad_Click(object sender, EventArgs e)
        {
            //Simulate a situation the user should be told about (i.e. error retrieving some list items)

            //The following line will be removed from our Release builds automatically
            logger.WriteDebugMethodStart();

            try
            {
                SPList list = SPContext.Current.Site.RootWeb.Lists.TryGetList("Announcements");
                if (Check.ThatIsNotNull(list))
                {

                    SPListItem itm = list.GetItemById(5);
                    itm["Title"] = "Hello World";
                    itm.Update();

                }
            }
            catch (Exception ex)
            {
                logger.HandleException(new CKSExceptionDetails(ex, CKSLoggingCategory.List)
                {
                    Display = ErrorDisplayType.StatusBar,
                    ThrowingControl = this,
                    UserText = "Item Title NOT Updated!",
                    StatusBarColor = CKSStatusBarColor.red
                });

            }
            finally
            {
                //The following line will be removed from our Release builds automatically
                logger.WriteDebugMethodEnd();


            }




        }


        #region Farm Demo

        //temporarily removed

        //void Bad_Click(object sender, EventArgs e)
        //{
        //    //Simulate a situation the user must know about
        //    //(i.e unable to save an item)

        //    try
        //    {
        //        logger.BeginScope();
        //        logger.WriteDebugMethodStart();
        //        SPList list = SPContext.Current.Site.RootWeb.Lists.TryGetList("Announcements");
        //        if (Check.ThatIsNotNull(list))
        //        {
        //            SPListItem itm = list.AddItem();
        //            itm["Title"] = "Hello World";
        //            itm["Body"] = "12345";
        //            itm["NonExistantField"] = "blah";
        //            itm.Update();

        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.HandleException(new CKSExceptionDetails(ex, CKSLoggingCategory.ListItem)
        //        {
        //            Display = ErrorDisplayType.Dialog,
        //            ThrowingControl = this
        //        });

        //    }
        //    finally
        //    {

        //        logger.WriteDebugMethodEnd();
        //        logger.EndScope();
        //    }
        //}

        //void ReallyBad_Click(object sender, EventArgs e)
        //{ //Simulate an unhandled exception
        //    //i.e. a site was deleted or incorrect URL specified
        //    // logger.BeginScope();

        //    logger.BeginScope();

        //    logger.WriteDebugMethodStart();
        //    using (SPSite siteCollection = new SPSite(InvalidUrl))
        //    {
        //        //Works fine if a valid URL is used, fails if not

        //    }
        //    logger.WriteDebugMethodEnd();

        //    logger.EndScope();
        //}




        //void Timings_Click(object sender, EventArgs e)
        //{//perform a random number of SP operations just to kill some time
        //    timer = logger.LogElapsedTimeStart("Random Delay");
        //    SPList list = null;
        //    int counter = 0;
        //    for (int i = 0; i < new Random().Next(5, 10); i++)
        //    {
        //        list = SPContext.Current.Web.Lists.TryGetList("SandboxLog");
        //        if (Check.ThatIsNotNull(list))
        //        {
        //            counter = list.ItemCount;
        //        }
        //    }
        //    logger.LogElapsedTimeStop(timer);
        //    logger.EndScope();
        //}


        #endregion   Farm Demo

        #region Set Up UI

        public enum ErrorType
        {
            All,
            ReallyBad,
            Bad,
            NotSoBad,
            NoBigDeal
        }

        [WebBrowsable(true),
        WebDisplayName("Type of Error"),
        Personalizable(PersonalizationScope.Shared),
        Category("CKS:API")]
        public ErrorType TypeOfError { get; set; }

        private string _invalidURL = "http://invalid_url";
        [WebBrowsable(true),
        WebDisplayName("Invalid URL for use with 'Really Bad Thing' error"),
        Personalizable(PersonalizationScope.Shared),
        Category("CKS:API")]
        public string InvalidUrl
        {
            get { return _invalidURL; }
            set { _invalidURL = value; }
        }



        protected override void CreateChildControls()
        {
            Controls.Add(new LiteralControl("<span style='font-size:large;text-decoration:underline'>Sandbox</span><br /><br />"));


            #region Farm Demo
            //temporarily removed
            //if (TypeOfError == ErrorType.All || TypeOfError == ErrorType.ReallyBad)
            //{
            //    Button ReallyBad = new Button()
            //    {
            //        Text = "Simulate an unhandled exception"
            //    };
            //    ReallyBad.Click += new EventHandler(ReallyBad_Click);
            //    Controls.Add(ReallyBad);
            //    Controls.Add(new LiteralControl("&nbsp;&nbsp;<span style='font-size:smaller'>(Things have gone really wrong)</span><br /><br />"));
            //}

            //if (TypeOfError == ErrorType.All || TypeOfError == ErrorType.Bad)
            //{
            //    Button Bad = new Button()
            //    {
            //        Text = "In the User's Face"
            //    };

            //    Bad.Click += new EventHandler(Bad_Click);
            //    Controls.Add(Bad);
            //    Controls.Add(new LiteralControl("&nbsp;&nbsp;<span style='font-size:smaller'>(Simulate a situation the user must know about)</span><br /><br />"));
            //}
            #endregion

            if (TypeOfError == ErrorType.All || TypeOfError == ErrorType.NotSoBad)
            {
                Button NotSoBad = new Button()
                {
                    Text = "Not So Bad"
                };

                NotSoBad.Click += new EventHandler(NotSoBad_Click);
                Controls.Add(NotSoBad);
                Controls.Add(new LiteralControl("&nbsp;&nbsp;<span style='font-size:smaller'>(Simulate a situation the user should be told about, but we don't need to be quite so visible about it)</span><br /><br />"));
            }

            if (TypeOfError == ErrorType.All || TypeOfError == ErrorType.NoBigDeal)
            {
                Button NoBigDeal = new Button()
                {
                    Text = "Handle, Log and Continue"
                };

                NoBigDeal.Click += new EventHandler(NoBigDeal_Click);
                Controls.Add(NoBigDeal);
                Controls.Add(new LiteralControl("&nbsp;&nbsp;<span style='font-size:smaller'>(Simulate a situation we can recover from)</span><br /><br />"));
            }

            #region Farm Demo
            //temporarily removed
            //Button Timings = new Button()
            //{
            //    Text = "Metrics"

            //};
            //Timings.Click += new EventHandler(Timings_Click);

            //Controls.Add(Timings);

            #endregion



        }

        #endregion

    }
}
